package com.xj.driver.mqtt.subscriber;


import com.xj.driver.mqtt.subscriber.domain.StationSwitchManager;
import com.xj.driver.mqtt.subscriber.monitor.MessageBacklogMonitor;
import com.xj.driver.mqtt.subscriber.processor.MqttMessageProcessor;
import com.xj.driver.mqtt.subscriber.queue.MessageQueueManager;
import com.xj.driver.mqtt.service.UpBizService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * MQTT通信管理器 - 设备接入
 */
@Slf4j
@Component
public class MqttComManagerHandler implements MessageHandler {

    @Resource
    private UpBizService upBizService;

    // 核心组件
    private StationSwitchManager stationSwitchManager;
    private  MqttMessageProcessor messageProcessor;
    private  MessageQueueManager messageQueueManager;
    private MessageBacklogMonitor messageBacklogMonitor;


    @PostConstruct
    public void init() {
        this.stationSwitchManager = new StationSwitchManager();
        this.messageProcessor = new MqttMessageProcessor(upBizService, stationSwitchManager);

        this.messageBacklogMonitor = new MessageBacklogMonitor();
        this.messageQueueManager = new MessageQueueManager(messageProcessor::processMessage, messageBacklogMonitor);

        messageQueueManager.startProcessing();
        log.info("MQTT通信管理器初始化完成");
    }

    @PreDestroy
    public void destroy() {
        messageQueueManager.stopProcessing();
        log.info("MQTT通信管理器已关闭");
    }

    @ServiceActivator(inputChannel = "topic-commanager")
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        messageQueueManager.addMessage(message);
    }

    /**
     * 定时检查设备状态
     */
    @Scheduled(fixedRate = 10000)
    public void scheduledDeviceCheck() {
        stationSwitchManager.checkAndSwitch();
    }
}